<?php
declare(strict_types=1);

namespace Modules\Production\Http\Controllers;

use Catch\Base\CatchController as Controller;
use App\Services\RedisLockService;use Modules\Base\Repository\MaterialRepository;use Modules\Production\Models\StockTaskScan;
use Illuminate\Http\Request;use Modules\Production\Service\TaskScanService;


class StockTaskScanController extends Controller
{
    public function __construct(
        protected readonly StockTaskScan $model
    ){}

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        $list = $this->model->getList()->toArray();
        foreach ($list['data'] as &$val){
            $val['status'] = $val['push_kingdee'] == 1 ? '已备货' : '备货中';
            $val['material'] = MaterialRepository::findMaterial($val['material_no']);
        }
        return $list;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {

        $lockTag = 'BACK_DELETE_' . $id;
        $redisLock = new RedisLockService($lockTag,30);
        if(!$redisLock->lock()){
            throw new \Exception('删除中，请稍后重试！');
        }

        try{
            return TaskScanService::deleteScan($id);
        }catch (\Exception $e){
            throw $e;
        } finally {
            //释放锁
            $redisLock->unlock();
        }

    }
}
